﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SL8.SL;
using System.Json;
using System.Collections.ObjectModel;
using System.Collections.Generic;

namespace JsonViewer
{
    public class JsonNode : ObservableObject
    {
        private ObservableCollection<JsonNode> _children = new ObservableCollection<JsonNode>();
        private bool isLoadChildren = false;

        /// <summary>
        /// 属性名
        /// </summary>
        public string PropertyName
        {
            get
            {
                return this.GetCacheValue(o => o.PropertyName, default(string));
            }
            set
            {
                this.SetCacheValueAndValidate(o => o.PropertyName, value);
            }
        }

        /// <summary>
        /// 属性值
        /// </summary>
        public JsonValue PropertyValue
        {
            get
            {
                return this.GetCacheValue(o => o.PropertyValue, default(JsonValue));
            }
            set
            {
                this.SetCacheValueAndValidate(o => o.PropertyValue, value);
            }
        }

        public ObservableCollection<JsonNode> Children
        {
            get
            {
                if (!this.isLoadChildren)
                {
                    this.LoadChildren();
                }
                return this._children;
            }
        }

        private void LoadChildren()
        {
            this.isLoadChildren = true;

            if (this.PropertyValue != null)
            {
                if (this.PropertyValue.JsonType == JsonType.Number)
                {

                }
                else if (this.PropertyValue.JsonType == JsonType.Array)
                {
                    int index = 0;
                    foreach (JsonValue item in this.PropertyValue)
                    {
                        this.Children.Add(new JsonNode()
                        {
                            PropertyName = string.Format("[{0}]", index),
                            PropertyValue = item
                        });

                        index++;
                    }
                }
                else if (this.PropertyValue.JsonType == JsonType.Object)
                {
                    foreach (KeyValuePair<string, JsonValue> keyValue in this.PropertyValue)
                    {
                        this.Children.Add(new JsonNode()
                        {
                            PropertyName = keyValue.Key,
                            PropertyValue = keyValue.Value
                        });
                    }
                }
            }
        }
    }
}
